import datetime

from django.db.models import Q
from rest_framework.views import APIView
from movie.models import MovieRatings, MovieLikes, \
    MovieComments, CollectMovieDB
from api import user_api, movie_api, api, delay_work
from api.response import JsonError, JsonResponse

tag_thread_work = delay_work.tag_thread_work

Movie = movie_api.Movie()

emoution = Movie.emoution
movie_search_api = Movie.movie_search
# get_user_movie_comment = Movie.get_user_movie_comment
# get_user_search = Movie.get_user_search
# get_user_movie_rating = Movie.get_user_movie_rating
# get_user_movie_brow = Movie.get_user_movie_brow
# get_user_like = Movie.get_user_like

isNotLogin = user_api.User().isNotLogin
get_ip = api.Api().get_ip



# Create your views here.
def movie_search(request):
    return JsonResponse(movie_search_api(request))


# 用户为电影评分  参数（评分，电影id）
class MovieRating(APIView):
    def get(self, request, *args, **kwargs):
        # 判断是否登录
        if isNotLogin(request):
            return JsonError("请先登录！")
        try:
            # 判断非空
            rating = int(request.GET.get("rating"))
            movie_id = int(request.GET.get("movieId"))
            if not rating or not movie_id:
                raise Exception
        except:
            return JsonError("请确认请求参数无误！")
        user_id = request.session.get("user_id")
        # 拿到指定用户对某一电影的评分
        rating_rs = MovieRatings.objects.filter(Q(user_id=user_id) & Q(movie_id=movie_id))
        if rating_rs.exists():
            tag_thread_work("user_rating_tag", user_id=user_id, movie_id=movie_id, old_rating=rating_rs.first().rating,
                            rating=rating, tag_sign="again")
            # 更新评分和更新时间
            rating_rs.update(rating=rating, rating_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        else:
            if not CollectMovieDB.objects.filter(movie_id=movie_id).exists():
                return JsonError("电影信息不存在，评分失败！")
            tag_thread_work("user_rating_tag", user_id=user_id, movie_id=movie_id, rating=rating, tag_sign="init")
            # 为用户创建电影评分
            MovieRatings.objects.create(user_id=user_id, movie_id=movie_id, rating=rating)
        return JsonResponse({"msg": "感谢您的评分！", "url": ""})

    def post(self, request, *args, **kwargs):
        return JsonError("不支持POST请求！")


# 用户为电影收藏  参数（电影id）
class MovieLike(APIView):
    def get(self, request, *args, **kwargs):
        if isNotLogin(request):
            return JsonError("请先登录！")
        try:
            movie_id = int(request.GET.get("movieId"))
            if not movie_id:
                raise Exception
        except:
            return JsonError("请确认请求参数无误！")
        user_id = request.session.get("user_id")
        like_rs = MovieLikes.objects.filter(Q(user_id=user_id) & Q(movie_id=movie_id))
        # 存在数据由两种状态，不存在则只有不收藏一种状态
        if like_rs.exists():
            like_rs1 = like_rs.first()
            if like_rs1.status:
                like_rs.update(status=0)
                tag_thread_work("user_like_tag", user_id=user_id, movie_id=movie_id, tag_sign="cancel")
                msg = "取消收藏成功！"
            else:
                tag_thread_work("user_like_tag", user_id=user_id, movie_id=movie_id, tag_sign="init")
                like_rs.update(like_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), status=1)
                msg = "收藏成功！"
        else:
            # 每次都得怀疑一下是不是电影出问题了
            if CollectMovieDB.objects.filter(movie_id=movie_id).exists():
                # 不存在所以创建数据
                tag_thread_work("user_like_tag", user_id=user_id, movie_id=movie_id, tag_sign="init")
                MovieLikes.objects.create(user_id=user_id, movie_id=movie_id, status=1)
                msg = "收藏成功！"
            else:
                return JsonError("电影信息不存在，收藏失败！")
        return JsonResponse({"msg": msg, "url": ""})

    def post(self, request, *args, **kwargs):
        return JsonError("不支持POST请求！")


# 用户为电影评论
class MovieComment(APIView):
    def get(self, request, *args, **kwargs):
        return JsonError("不支持GET请求！")

    def post(self, request, *args, **kwargs):
        if isNotLogin(request):
            return JsonError("请先登录！")

        title = request.POST.get("title")
        user_id = request.session.get("user_id")
        user_uname = request.session.get("user_uname")
        movie_name = request.POST.get("movie_title")
        movie_id = request.POST.get("movie_id")
        content_text = request.POST.get("content_text")
        ip = get_ip(request)
        # 非空判断
        if movie_id and content_text and title:
            # 获取句子的情感倾向值
            emotion = emoution(content_text)
            if not CollectMovieDB.objects.filter(movie_id=movie_id).exists():
                return JsonError("电影信息不存在，评论失败！")
            tag_thread_work("user_comment_tag", user_id=user_id, movie_id=movie_id, emotion=emotion, tag_sign="add")
            movie_comment = MovieComments.objects.create(user_id=user_id, movie_id=movie_id, userName=user_uname,
                                                         title=title, movieName=movie_name, content=content_text,
                                                         emotion=emotion, ip=ip)
        else:
            return JsonError("评论失败，标题和内容不能为空！")
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        comment = {"userName": user_uname, "user": str(user_id), "comment_time": now, "title": title,
                   "content": content_text, "id": movie_comment.id}
        return JsonResponse({"msg": "评论成功！", "url": "", "comment": comment})


# 删除电影评论
class MovieCommentDelete(APIView):
    def get(self, request, *args, **kwargs):
        if isNotLogin(request):
            return JsonError("请先登录！")
        try:
            comment_id = int(request.GET.get("comment_id"))
            if not comment_id:
                raise Exception
        except:
            return JsonError("请确认请求参数无误！")
        user_id = request.session.get("user_id")
        comment_rs = MovieComments.objects.filter(Q(user_id=user_id) & Q(id=comment_id))
        # 用是否存在来判断是否是该用户的评论
        if comment_rs.exists():
            tag_thread_work("user_comment_tag", user_id=user_id, movie_id=comment_rs.first().movie_id,
                            emotion=comment_rs.first().emotion, tag_sign="delete")
            # 没有真正删除，只是将状态设置为0
            comment_rs.update(status=0)
            return JsonResponse({"msg": "评论删除成功！", "url": ""})
        else:
            return JsonError("您没有权限删除该评论！")

    def post(self, request, *args, **kwargs):
        return JsonError("不支持POST请求！")

